
var ConstantData = require('../common/constant_data.js');
var fun_aes = require("fun_aes");
// var key = "41262A326850";

function hexToArray(hex) {
  let arr = [];
  if(!hex) {
     return arr;
  }
  for(let i=0;i<hex.length;i+=2) {
    let hv = hex[i] + hex[i+1];
    let v = parseInt(hv,16);
    arr.push(v);
  }
  return arr;
}

// 加密
function aesEncrypt(that,content) {   //key和code需要使用十进制的数组表示
  let code = hexToArray(content);
  let pwd = that.data.blepwd;  
  var o = hexToArray(pwd);    //key的密钥10进制
  
  var a = this;
  var t = fun_aes.CryptoJS.enc.int8array.parse(o);
  var r = fun_aes.CryptoJS.enc.int8array.parse(code);
  var n = (r.toString(fun_aes.CryptoJS.enc.Base64),
    fun_aes.CryptoJS.AES.encrypt(r, t, {
      iv: [],
      mode: fun_aes.CryptoJS.mode.ECB,
      padding: fun_aes.CryptoJS.pad.NoPadding
    }));
  let w = n.ciphertext.toString();  
  console.log("pwd:" + pwd + ";w:" + w);
  return w;
}

//解密
function aesDecrypt(that, content) {
  let code = hexToArray(content);
  let pwd = that.data.blepwd;  
  var o = hexToArray(pwd);    //key的密钥10进制

  var a = this,
    l = code,
    t = fun_aes.CryptoJS.enc.int8array.parse(o),
    r = fun_aes.CryptoJS.enc.int8array.parse(l).toString(fun_aes.CryptoJS.enc.Base64),
    n = fun_aes.CryptoJS.AES.decrypt(r, t, {
      iv: [],
      mode: fun_aes.CryptoJS.mode.ECB,
      padding: fun_aes.CryptoJS.pad.NoPadding
    });
  n = n.toString().toUpperCase();
  console.log("pwd:" + pwd + ";n:" + n);
  return n;
}



module.exports.aesEncrypt = aesEncrypt
module.exports.aesDecrypt = aesDecrypt
